#include "znx_http_headers.h"


void
znx_http_headers_add(znx_http_headers_t *headers, znx_http_header_t *header)
{
    znx_queue_insert_tail(&headers->head, &header->queue);
}


void
znx_http_headers_set(znx_http_headers_t *headers, znx_http_header_t *header)
{
    znx_http_header_t   *tmp_header;
    znx_http_header_t   *match_header = NULL;
    znx_queue_t         *q;

    q = znx_queue_head(&headers->head);
    while(q != &headers->head) {
        tmp_header = znx_queue_data(q, znx_http_header_t, queue);
        q = q->next;

        if (headers->cmp_handle(&header->key, &tmp_header->key) == 0) {
            if (!match_header) {
                match_header = tmp_header;
                continue;
            }
            znx_queue_remove(&tmp_header->queue);
        }
    }

    if (match_header) {
        match_header->val = header->val;
        return;
    }

    znx_queue_insert_tail(&headers->head, &header->queue);
}


znx_http_header_t *
znx_http_headers_get(znx_http_headers_t *headers, znx_str_t *key, size_t index)
{
    znx_http_header_t   *header;
    znx_queue_t         *q;
    size_t              i = 0;

    if (index < 0) {
        index = 0;
    }

    q = znx_queue_head(&headers->head);
    while (q != &headers->head) {
        header = znx_queue_data(q, znx_http_header_t, queue);
        q = q->next;

        if (headers->cmp_handle(key, &header->key) == 0) {
            if (i == index) {
                return header;
            }
            i++;
        }
    }

    return NULL;
}


void
znx_http_headers_del_once(znx_http_headers_t *headers, znx_str_t *key)
{
    znx_http_header_t       *header;
    znx_queue_t             *q;

    q = znx_queue_head(&headers->head);
    while (q != &headers->head) {
        header = znx_queue_data(q, znx_http_header_t, queue);
        q = q->next;

        if (headers->cmp_handle(key, &header->key) == 0) {
            znx_queue_remove(&header->queue);
            return;
        }
    }
}


void
znx_http_headers_del(znx_http_headers_t *headers, znx_str_t *key)
{
    znx_http_header_t       *header;
    znx_queue_t             *q;

    q = znx_queue_head(&headers->head);
    while (q != &headers->head) {
        header = znx_queue_data(q, znx_http_header_t, queue);
        q = q->next;

        if (headers->cmp_handle(key, &header->key) == 0) {
            znx_queue_remove(&header->queue);
        }
    }
}
